﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Portal.Nhibernate.Repository;

namespace Portal.Web.Areas.Admin.Controllers
{
    public class UserController : BaseAdminController
    {
        private readonly IUserRepository<IUser> _userRepository;
        public UserController(IUserRepository<IUser> userRepository)
        {
            _userRepository = userRepository;
        }

        public UserController()
        {
            _userRepository = new UserRepository();
        }
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ChangePassword()
        {
            if (Request.IsAjaxRequest())
                return View("ChangePasswordControl");
            return View();
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChangePassword(string oldPassword, string newPassword, FormCollection formCollection)
        {
            if (string.IsNullOrEmpty(oldPassword.NullSafe().Trim()))
                return Json(new AjaxResult { state = false, message = "原密码不能为空" });
            if (string.IsNullOrEmpty(newPassword.NullSafe().Trim()))
                return Json(new AjaxResult { state = false, message = "新密码不能为空" });
            //查询用户实例
            var model = _userRepository.Get().FirstOrDefault(o => o.Account == CurrentUserName && o.Password == oldPassword);
            if (model == null)
            {
                if (Request.IsAjaxRequest())
                    return Json(new AjaxResult { message = "原密码不正确", state = false });
                ViewData["Result"] = new AjaxResult { message = "原密码不正确", state = false };
                return View();
            }
            model.Password = newPassword;
            _userRepository.Update(model);
            _userRepository.Save();
            if (Request.IsAjaxRequest())
                return Json(new AjaxResult { message = "修改成功", state = true });
            ViewData["Result"] = new AjaxResult { message = "修改成功", state = true };
            return View();
        }

    }
}
